package org.vectrics.company.web.struts;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.vectrics.common.util.DateSync;
import org.vectrics.company.Company;
import org.vectrics.company.CompanyPerson;
import org.vectrics.company.CompanyPersonRole;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.struts.Request;
import org.vectrics.user.Person;


public class ShowCompanyPersonRoleAction extends RequestFormAction {
    private transient static Logger log = Logger.getLogger(ShowCompanyPersonRoleAction.class);
	
	protected String fillForm(ActionForm formIn, Request request, HttpServletResponse response) {
		String mapCode = "success";
		CompanyPersonRoleForm form = (CompanyPersonRoleForm)formIn;
		String companyIdParam = request.getParameter("companyId");
		String personIdParam = request.getParameter("personId");
		
		String companyPersonRoleIdParam = request.getParameter("companyPersonRoleId");
		String roleType = request.getParameter("roleTypeCode");

		request.setAttribute("companyPersonRoleId", companyPersonRoleIdParam);
		
		form.setRoleType(roleType);
		form.setTitle(this.getPhrase("phrase.employee.title.default", request.getLocale()));

		CompanyPerson companyPerson = null;
		CompanyPersonRole companyPersonRole = null;
		Company company = CoreServiceLocator.getCompanyService().findCompany(new Long(companyIdParam));
		Person person = CoreServiceLocator.getPersonService().findPersonById(new Long(personIdParam));
		companyPerson = CoreServiceLocator.getCompanyService().findCompanyPerson(company, person);
		
		if (companyPerson != null) {
			form.setPersonName(companyPerson.getPerson().getName());
			form.setCompanyName(companyPerson.getCompany().getName());
			if (companyPersonRoleIdParam != null) {
				companyPersonRole = companyPerson.findRole(new Long(companyPersonRoleIdParam));
				form.setTitle(companyPerson.getTitle());
				form.setRoleType(companyPersonRole.getRoleType().getCode());
				if (companyPersonRole.getDateStart() != null)
					form.setDateStart(CoreServiceLocator.getDateFormat().getDateFormatRoundToDay(request.getLocale()).format(companyPersonRole.getDateStart()));
				else
					form.setDateStart(CoreServiceLocator.getDateFormat().getDateFormatRoundToDay(request.getLocale()).format(DateSync.getCurrentTime()));
				if (companyPersonRole.getDateEnd() != null)
					form.setDateEnd(CoreServiceLocator.getDateFormat().getDateFormatRoundToDay(request.getLocale()).format(companyPersonRole.getDateEnd()));
			} else {
				form.setDateStart(CoreServiceLocator.getDateFormat().getDateFormatRoundToDay(request.getLocale()).format(DateSync.getCurrentTime()));
			}
		}
		return(mapCode);
	}

	protected ActionForm createForm() {
		ActionForm form = new CompanyPersonRoleForm();
		return(form);
	}
	
}
